from service.das.strategy_bind_setting_das import StrategyBindingService
from service.setting_service import DataDictionaryService
from views.common.translator import Translator
from views.template_page_view import BasePageTemplateView, FormItemDto, MainCardTemplate


class CommonSettingView(BasePageTemplateView):

    def __init__(self, parent=None):
        t = Translator()
        super().__init__("CommonSettingView", parent=parent)

    def doInitAndUpdate(self):

        # 顶部按钮
        card = MainCardTemplate("操作按钮", form, stretch, self.view)

        # 添加一个报表
        dataMapService = DataDictionaryService()
        form_items = dataMapService.getAllCommonSetting()
        self.addFromTemplate(form_items, "基础配置表单", self.commonSettingCallback)

        # 查询策略列表
        dataMapService = StrategyBindingService()

    def commonSettingCallback(self, form_data: list[FormItemDto]):
        AntLogger.info("Form Data:", form_data)
        """
        接收 FormItemDto 列表并保存到数据库。
        """

        dataMap = DataDictionaryService()
        for item in form_data:
            # 调用 DataDictionaryService 的保存方法
            try:
                dataMap.saveOrUpdateCommonSetting(
                    item.form_key, item.form_value, item.form_desc
                )
                AntLogger.info(f"Saved field: {item.form_key} - {item.form_value}")
            except Exception as e:
                AntLogger.info(f"Failed to save field {item.form_key}. Error: {e}")
